<template>

  <div id="teamCardList">
    <van-skeleton title avatar :row="3" :loading="props.loading" v-for="team in props.teamList">
      <van-card
          :desc="team.description"
          thumb="https://img1.baidu.com/it/u=413643897,2296924942&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500"
          :title="team.name"
      >
        <template #tags>
          <van-tag plain type="danger" style="margin-right: 8px;margin-top: 8px">{{
              teamStatusEnum[team.status]
            }}
          </van-tag>
        </template>
        <template #bottom>
          <div>
            {{ `队伍人数：${team.hasJoinNum}/${team.maxNum}` }}
          </div>
          <div v-if="team.expireTime">
            {{ '过期时间：' + team.expireTime }}
          </div>
          <div>
            {{ '创建时间：' + team.createTime }}
          </div>
        </template>
        <template #footer>
          <van-button size="mini" plain type="primary" @click="preJoinTeam(team)"
                      v-if="team.userId !== currentUser?.id && !team.hasJoin">
            加入队伍
          </van-button>
          <van-button v-if="team.userId === currentUser?.id" size="mini" plain
                      type="success"
                      @click="doUpdateTeam(team.id)">更新队伍
          </van-button>
          <van-button v-if="team.hasJoin"
                      size="mini" plain
                      type="warning"
                      @click="doQuitTeam(team.id)">退出队伍
          </van-button>
          <van-button v-if="team.userId === currentUser?.id" size="mini" plain
                      type="danger"
                      @click="doDeleteTeam(team.id)">解散队伍
          </van-button>
        </template>
      </van-card>
    </van-skeleton>
    <van-skeleton title avatar :row="3" :loading="props.loading"/>
    <van-skeleton title avatar :row="3" :loading="props.loading"/>
    <van-skeleton title avatar :row="3" :loading="props.loading"/>
    <van-skeleton title avatar :row="3" :loading="props.loading"/>

    <van-dialog v-model:show="showPasswordDialog" title="请输入密码" show-cancel-button
                @confirm="doJoinTeam" @cancel="doJoinCancel">
      <van-field v-model="password" placeholder="请输入密码"/>
    </van-dialog>

  </div>

</template>

<script setup lang="ts">
// @ts-ignore
import {defineProps, onMounted, ref, withDefaults} from "vue";
import {TeamType} from "../models/team";
import {teamStatusEnum} from "../constants/team";
// @ts-ignore
import {formatDate} from '../utils/date.js';
// @ts-ignore
import myAxios from "../plugins/myAxios";
// @ts-ignore
import {Toast} from "vant";
import {getCurrentUser} from "../services/user";
// @ts-ignore
import {useRouter} from "vue-router";

const currentUser = ref();

interface TeamCardListProps {
  teamList: TeamType[];
  loading: boolean;
}

const props = withDefaults(defineProps<TeamCardListProps>(), {
  // 当userList为null时，将userList赋值为[]数组，防止报错
  teamList: [],
  loading: true
});

const router = useRouter();
const showPasswordDialog = ref(false);
const password = ref('');
const joinTeamId = ref(-1);

onMounted(async () => {
  const res = formatDate(new Date());
  console.log(res);

  currentUser.value = await getCurrentUser();

})

// 加入队伍
const doJoinTeam = async () => {
  if (!joinTeamId.value) {
    return;
  }
  const res = await myAxios.post('/team/join', {
    teamId: joinTeamId.value,
    password: password.value
  });
  if (res?.code === 0) {
    Toast.success('加入成功');
  } else {
    Toast.fail('加入失败' + (res.description ? `,${res.description}` : ''));
  }
  doJoinCancel();
};

const preJoinTeam = (team: TeamType) => {
  joinTeamId.value = team.id;
  if (team.status === 0) {
    doJoinTeam();
  } else if (team.status === 2) {
    showPasswordDialog.value = true;
  }
}

/**
 * 更新队伍
 * @param id
 */
const doUpdateTeam = (id: number) => {
  router.push({
    path: '/team/update',
    query: {
      id
    }
  })
};

/**
 * 退出队伍
 * @param id
 */
const doQuitTeam = async (id: number) => {
  const res = await myAxios.post('/team/quit', {
    teamId: id
  });
  if (res?.code === 0) {
    Toast.success('操作成功');
  } else {
    Toast.fail('操作失败' + (res.description ? `,${res.description}` : ''));
  }
};

const doJoinCancel = () => {
  joinTeamId.value = -1;
  password.value = '';
}
/**
 * 解散队伍
 * @param id
 */
const doDeleteTeam = async (id: number) => {
  const res = await myAxios.post('/team/delete', {
    id
  });
  if (res?.code === 0) {
    Toast.success('操作成功');
  } else {
    Toast.fail('操作失败' + (res.description ? `,${res.description}` : ''));
  }
};
</script>

<style scoped>
#teamCardList :deep(.van-image__img ) {
  height: 128px;
  object-fit: unset;
}
</style>
